from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.apis import api_router
from app.core.config import settings, TORTOISE_ORM
from app.core.events import create_start_app_handler, create_stop_app_handler
from tortoise.contrib.fastapi import register_tortoise

from app.core.middleware import init_middleware
from app.core.logging import setup_logging
from app.schemas.response import setup_exception_handlers


def create_application() -> FastAPI:
    setup_logging()
    application = FastAPI(
        title=settings.PROJECT_NAME,
        description=settings.PROJECT_DESCRIPTION,
        version=settings.VERSION,
    )

    # Add CORS middleware
    application.add_middleware(
        CORSMiddleware,
        allow_origins=(
            [str(origin) for origin in settings.BACKEND_CORS_ORIGINS] if settings.BACKEND_CORS_ORIGINS else ["*"]
        ),
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    register_tortoise(
        application,
        config=TORTOISE_ORM,
        generate_schemas=False,
        add_exception_handlers=True,
    )

    # 初始化中间件们
    init_middleware(application)
    # 设置异常处理器
    setup_exception_handlers(application)
    # 设置事件处理器
    application.add_event_handler("startup", create_start_app_handler(application))
    application.add_event_handler("shutdown", create_stop_app_handler(application))

    # 注册路由
    application.include_router(api_router, prefix=settings.API_V1_STR)
    return application


app = create_application()
